package com.zipking.cloud.springbootmybatis.config;

import com.zipking.cloud.springbootmybatis.anntention.Method;
import com.zipking.cloud.springbootmybatis.service.BaseService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Configuration
public class ApiCoreFactory {
    //工厂对象
    public static Map<String, BaseService> baseServiceMapFacyory;
    @Bean
    public ApplicationContext setBaseServiceBeanFactory(ApplicationContext  applicationContext){
        //从上下文提前BaseService的实现类(须含有@Service这类会触发bean注册的注解)
        Map<String, BaseService> beans = applicationContext.getBeansOfType(BaseService.class);
        //单列设计 初始化map扩展大小
        if(Objects.isNull(baseServiceMapFacyory)){
            baseServiceMapFacyory=new HashMap<>(beans.size());
        }
        for(Map.Entry<String,BaseService> map :beans.entrySet()){
            Method method = map.getValue().getClass().getAnnotation(Method.class);
            if(Objects.nonNull(method)){
                baseServiceMapFacyory.putIfAbsent(method.name(),map.getValue());
            }
        }
        return applicationContext;
    }
    /**
     * 从工厂对象中提取BaseService
     * @param method
     * @return
     */
    public static  BaseService getBaseService(String method){
        BaseService baseService = baseServiceMapFacyory.get(method);
        return  baseService;
    }
}
